package cn.com.inossem.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.Button;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMapLoadedCallback;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.inossem.db.DatabaseHelper;
import cn.com.inossem.fragment.MyFriendsFragment;
import cn.com.inossem.model.UserInfo;

public class MapActivity extends Activity implements OnMapLoadedCallback {

	MapView mMapView = null;
	BaiduMap mBaiduMap;
	MapStatus ms;
	private InfoWindow mInfoWindow;

	// private Marker mMarkerA;
	private List<DianInfo> listmarker;

	BitmapDescriptor bd = null;
	public static List<UserInfo> maplistfriends = new ArrayList<UserInfo>();

	class DianInfo {

		public DianInfo() {

		}

		private Marker marker;
		private String friendsnum;
		private List<String> listid = new ArrayList<String>();

		public List<String> getListid() {
			return listid;
		}

		public void setListid(List<String> listid) {
			this.listid = listid;
		}

		public Marker getMarker() {
			return marker;
		}

		public void setMarker(Marker marker) {
			this.marker = marker;
		}

		public String getFriendsnum() {
			return friendsnum;
		}

		public void setFriendsnum(String friendsnum) {
			this.friendsnum = friendsnum;
		}

	}

	public DianInfo dianinfo;

	// private ClusterManager<MyItem> mClusterManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 在使用SDK各组件之前初始化context信息，传入ApplicationContext
		// 注意该方法要再setContentView方法之前实现
		SDKInitializer.initialize(getApplicationContext());
		setContentView(R.layout.map_layout);

		// try {
		// CreateText();
		// } catch (IOException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }

//		bd = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);
		bd = BitmapDescriptorFactory.fromResource(R.drawable.map_pin_fill_20);

		// 获取地图控件引用
		mMapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();

		MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(5.0f);
		mBaiduMap.setMapStatus(msu);

		initOverlay();

		mBaiduMap.setOnMapClickListener(new OnMapClickListener() {

			@Override
			public boolean onMapPoiClick(MapPoi arg0) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public void onMapClick(LatLng arg0) {
				// TODO Auto-generated method stub
				// LatLng ll = marker.getPosition();
				// LatLng llNew = new LatLng(ll.latitude + 0.005,
				// ll.longitude + 0.010);
				// marker.setPosition(llNew);
				mBaiduMap.hideInfoWindow();
			}
		});

		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
			public boolean onMarkerClick(final Marker marker) {
				Button button = new Button(getApplicationContext());
				button.setTextColor(Color.BLACK);
				button.setBackgroundResource(R.drawable.popup);
				OnInfoWindowClickListener listener = null;
				for (int i = 0; i < listmarker.size(); i++) {
					if (marker == listmarker.get(i).getMarker()) {
						button.setText("您有" + listmarker.get(i).getFriendsnum()
								+ "个好友在这里");
//						button.setTextSize(13);
						dianinfo = listmarker.get(i);
						listener = new OnInfoWindowClickListener() {
							public void onInfoWindowClick() {
								maplistfriends = new ArrayList<UserInfo>();

								for (int k = 0; k < MyFriendsFragment.u_list
										.size(); k++) {
									for (int j = 0; j < dianinfo.getListid()
											.size(); j++) {
										if (MyFriendsFragment.u_list.get(k)
												.getId() == Integer
												.parseInt(dianinfo.getListid()
														.get(j))) {
											maplistfriends
													.add(MyFriendsFragment.u_list
															.get(k));
										}
									}
								}
								Intent intent = new Intent(MapActivity.this,
										FriendActivityList.class);
								MapActivity.this.startActivity(intent);
							}
						};
						LatLng ll = marker.getPosition();
						mInfoWindow = new InfoWindow(BitmapDescriptorFactory
								.fromView(button), ll, -130, listener);
						mBaiduMap.showInfoWindow(mInfoWindow);
					}
				}

				return true;
			}
		});

		// ms = new MapStatus.Builder().target(new LatLng(22.200000,
		// 114.100000))
		// .zoom(8).build();
		// mBaiduMap = mMapView.getMap();
		// mBaiduMap.setOnMapLoadedCallback(this);
		// // 定义点聚合管理类ClusterManager
		// mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));
		// mClusterManager = new ClusterManager<MyItem>(this, mBaiduMap);
		// // 添加Marker点
		// addMarkers();
		// // 设置地图监听，当地图状态发生改变时，进行点聚合运算
		// mBaiduMap.setOnMapStatusChangeListener(mClusterManager);
	}

	Map<String, List<UserInfo>> maplist;

	public void initOverlay() {
		listmarker = new ArrayList<DianInfo>();
		maplist = new HashMap<String, List<UserInfo>>();

		// List<UserInfo> u_list
		for (int i = 0; i < MyFriendsFragment.u_list.size(); i++) {
			if (MyFriendsFragment.u_list.get(i).getProjectAddress() > 0
					|| MyFriendsFragment.u_list.get(i).getHomeAddress() > 0) {
				if (maplist.containsKey(MyFriendsFragment.u_list.get(i)
						.getProjectAddress() + "")
						&& MyFriendsFragment.u_list.get(i).getProjectAddress() > 0) {
					maplist.get(
							MyFriendsFragment.u_list.get(i).getProjectAddress()
									+ "").add(MyFriendsFragment.u_list.get(i));
				} else if (maplist.containsKey(MyFriendsFragment.u_list.get(i)
						.getHomeAddress() + "")
						&& MyFriendsFragment.u_list.get(i).getHomeAddress() > 0) {
					maplist.get(
							MyFriendsFragment.u_list.get(i).getHomeAddress()
									+ "").add(MyFriendsFragment.u_list.get(i));
				} else {
					List<UserInfo> list = new ArrayList<UserInfo>();
					list.add(MyFriendsFragment.u_list.get(i));
					if (MyFriendsFragment.u_list.get(i).getProjectAddress() > 0) {
						maplist.put(MyFriendsFragment.u_list.get(i)
								.getProjectAddress() + "", list);
					} else if (MyFriendsFragment.u_list.get(i).getHomeAddress() > 0) {
						maplist.put(MyFriendsFragment.u_list.get(i)
								.getHomeAddress() + "", list);
					}
				}
			} else {
				System.out.println("地址："
						+ MyFriendsFragment.u_list.get(i).getProjectAddress()
						+ "=="
						+ MyFriendsFragment.u_list.get(i).getHomeAddress());
			}
		}

		DatabaseHelper dh = new DatabaseHelper(this);
		SQLiteDatabase db = dh.getReadableDatabase();
		Cursor cursor = null;

		for (Map.Entry<String, List<UserInfo>> entry : maplist.entrySet()) {
			System.out.println("查询area_id=" + entry.getKey());
			cursor = db.query("t_areas", null, "area_id=" + entry.getKey(),
					null, null, null, null);
			String longitude = "";
			String latitude = "";
			if (cursor.moveToFirst()) {
				longitude = cursor
						.getString(cursor.getColumnIndex("longitude"));
				latitude = cursor.getString(cursor.getColumnIndex("latitude"));
			}
			System.out.println(longitude + "======" + latitude);
			LatLng llA = new LatLng(Double.parseDouble(longitude),
					Double.parseDouble(latitude));
			MarkerOptions ooA = new MarkerOptions().position(llA).icon(bd)
					.zIndex(9).draggable(true);
			Marker mMarkerA = (Marker) (mBaiduMap.addOverlay(ooA));

			DianInfo dian = new DianInfo();
			dian.setMarker(mMarkerA);
			dian.setFriendsnum(entry.getValue().size() + "");
			List<String> listid = new ArrayList<String>();
			for (int j = 0; j < entry.getValue().size(); j++) {
				listid.add(entry.getValue().get(j).getId() + "");
			}
			dian.setListid(listid);
			listmarker.add(dian);
		}

		if (null != cursor) {
			cursor.close();
		}
		db.close();
		dh.close();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
		mMapView.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
		mMapView.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		// 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
		mMapView.onPause();
	}

	/**
	 * 向地图添加Marker点
	 */
	// public void addMarkers() {
	// // 添加Marker点
	// LatLng llA = new LatLng(34.500000, 121.433333);
	// LatLng llB = new LatLng(22.200000, 114.100000);
	// LatLng llC = new LatLng(21.200000, 114.500000);
	// LatLng llD = new LatLng(39.906965, 116.401394);
	// LatLng llE = new LatLng(39.956965, 116.331394);
	// LatLng llF = new LatLng(30.200000, 120.200000);
	// LatLng llG = new LatLng(30.280000, 120.150000);
	//
	// List<MyItem> items = new ArrayList<MyItem>();
	// items.add(new MyItem(llA));
	// items.add(new MyItem(llB));
	// items.add(new MyItem(llC));
	// items.add(new MyItem(llD));
	// items.add(new MyItem(llE));
	// items.add(new MyItem(llF));
	// items.add(new MyItem(llG));
	//
	// mClusterManager.addItems(items);
	//
	// }

	/**
	 * 每个Marker点，包含Marker点坐标以及图标
	 */
	// public class MyItem implements ClusterItem {
	// private final LatLng mPosition;
	//
	// public MyItem(LatLng latLng) {
	// mPosition = latLng;
	// }
	//
	// @Override
	// public LatLng getPosition() {
	// return mPosition;
	// }
	//
	// @Override
	// public BitmapDescriptor getBitmapDescriptor() {
	// return BitmapDescriptorFactory
	// .fromResource(R.drawable.icon_gcoding);
	// }
	// }
	@Override
	public void onMapLoaded() {
		// TODO Auto-generated method stub
		ms = new MapStatus.Builder().zoom(7).build();
		mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));
	}

}
